﻿using System;
using System.Collections.Generic;
namespace _13.罗马数字转整数 {
    class Program {
        static void Main (string[] args) {
            Console.WriteLine ("Hello World!");
            Solution s = new Solution ();
            Console.WriteLine (s.GetIntByRomaNumber ("III"));
            Console.WriteLine (s.GetIntByRomaNumber ("IV"));
            Console.WriteLine (s.GetIntByRomaNumber ("IX"));

            Console.WriteLine (s.GetIntByRomaNumber ("LVIII"));
            Console.WriteLine (s.GetIntByRomaNumber ("MCMXCIV"));
        }
    }
    class Solution {
        //将罗马数字转化为整数
        public int GetIntByRomaNumber (string romaNumber) {

            var chars = romaNumber.ToCharArray ();
            var dict = new Dictionary<char, int> () { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 }, };
            int result = 0;
            //比较相邻的两位，如果左边位代表的值大于右边，使用加法
            //如果右边代表的值大于左边，使用减法，比如使用IV做演示
            for (int i = 0; i < chars.Length; i++) {
                if (i < chars.Length - 1 && (dict[chars[i]] < dict[chars[i + 1]])) {
                    result -= dict[chars[i]];
                } else {
                    result += dict[chars[i]];
                }
            }
            return result;
        }
    }
}